package com.gs.SynPatrolRep.activity.palBill;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.pickerview.view.OptionsPickerView;
import com.gs.SynPatrolRep.R;
import com.gs.SynPatrolRep.activity.ImagePreviewActivity;
import com.gs.SynPatrolRep.activity.base.BaseActivity;
import com.gs.SynPatrolRep.activity.event.CreateReportActivity;
import com.gs.SynPatrolRep.adapter.PalBillItemAdapter;
import com.gs.SynPatrolRep.adapter.PatrolItemPhotoAdapter;
import com.gs.SynPatrolRep.adapter.base.BaseAdapter;
import com.gs.SynPatrolRep.apiresult.ApiResultData;
import com.gs.SynPatrolRep.apiresult.PagedList;
import com.gs.SynPatrolRep.constant.AllConstants;
import com.gs.SynPatrolRep.control.LinearLayoutManager;
import com.gs.SynPatrolRep.db.dto.CreatePalBillItemDto;
import com.gs.SynPatrolRep.db.dto.PalBillItemDto;
import com.gs.SynPatrolRep.db.dto.PalBillOptDto;
import com.gs.SynPatrolRep.db.dto.ShortDto;
import com.gs.SynPatrolRep.db.query.PalBillItemQuery;
import com.gs.SynPatrolRep.dialog.ComboPicDialog;
import com.gs.SynPatrolRep.dialog.LoadingDialogUtils;
import com.gs.SynPatrolRep.dialog.ShortDialog;
import com.gs.SynPatrolRep.dialog.ToastDialogUtils;
import com.gs.SynPatrolRep.presenter.PalBillItemPresenter;
import com.gs.SynPatrolRep.util.DateUtil;
import com.gs.SynPatrolRep.util.FileUtils;
import com.gs.SynPatrolRep.util.ImageUtil;
import com.gs.SynPatrolRep.util.OKHttpUtil;
import com.gs.SynPatrolRep.util.PhotoUtil;
import com.gs.SynPatrolRep.util.WindowUtil;
import com.gs.SynPatrolRep.view.IPalBillItemView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class PalBillItemActivity extends BaseActivity<IPalBillItemView, PalBillItemPresenter>
        implements IPalBillItemView {
    private List<PalBillItemDto> listChoice;
    private PalBillItemAdapter adapterChoice;
    private List<CreatePalBillItemDto.ExctPhoto> listPhoto;
    private PatrolItemPhotoAdapter adapterPhoto;
    private int choice, hour, minute, firstPos;
    private CheckBox rbPoint;
    private EditText etPoint;
    private List<ShortDto> list;
    private PalBillItemQuery query;
    private String billId, siteId, siteName;
    private CreatePalBillItemDto.Event event;
    private List<CreatePalBillItemDto.CreatePalBillItemFdbackDto> listFd;
    private List<String> first, second, third;

    @Override
    public void initView() {
        Bundle bundle = getIntent().getBundleExtra(AllConstants.WHAT);
        if (bundle != null) {
            billId = bundle.getString(AllConstants.ID);
            siteId = bundle.getString(AllConstants.WHAT);
            siteName = bundle.getString(AllConstants.NAME) == null ? "" : bundle.getString(AllConstants.NAME);
        }
        query = new PalBillItemQuery();
        query.setBillId(billId);
        query.setSiteId(siteId);
        toolBarTitle = findViewById(R.id.toolBarTitle);
        toolBarTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v.getId() == R.id.item_back) {
                    finish();
                }
            }
        });
        event = new CreatePalBillItemDto.Event();
        listFd = new ArrayList<>();
        TextView tvName = fd(R.id.tv_name);
        tvName.setText(siteName);
        RecyclerView rvChoice = findViewById(R.id.rv_choice);
        listChoice = new ArrayList<>();
        adapterChoice = new PalBillItemAdapter(this, listChoice, R.layout.rvitem_patrolitem);
        adapterChoice.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClickListener(View v, int pos) {
                choice = pos;
                PalBillItemDto palBillItemDto = listChoice.get(pos);
                // 多選一
                if (palBillItemDto.getEnterType() == 2 &&
                        palBillItemDto.getOpts() != null &&
                        !palBillItemDto.getOpts().isEmpty()) {
                    if (list == null || list.size() < 1) {
                        List<PalBillOptDto> opts = palBillItemDto.getOpts();
                        list = new ArrayList<>();
                        for (int i = 0; i < opts.size(); i++) {
                            list.add(new ShortDto(opts.get(i).getOptName(), opts.get(i).getOptName()));
                        }
                    }
                    new ShortDialog(PalBillItemActivity.this, list, R.string.p_sel, palBillItemDto.getDefVal(), new ShortDialog.IChoiceListener() {
                        @Override
                        public void getChoiceFromDialog(ShortDto bean) {
                            adapterChoice.setChoiceText(choice, palBillItemDto.getItemId(), bean.getName());
                        }
                    }).show();
                }
                // 輸入時間
                else if (palBillItemDto.getEnterType() == 3 && palBillItemDto.getEnterLimit() == 3) {
                    getList();
                    showDate(pos);
                    WindowUtil.getInstance().hideSoftInput(getWindow().getDecorView());
                }
            }
        });
        rvChoice.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        rvChoice.setAdapter(adapterChoice);
        rvChoice.setItemAnimator(null);
        RecyclerView rvPhoto = findViewById(R.id.rv_pic);
        listPhoto = new ArrayList<>();
        adapterPhoto = new PatrolItemPhotoAdapter(this, this, listPhoto, 9);
        adapterPhoto.setOnItemClickListener(new PatrolItemPhotoAdapter.OnItemClickListener() {
            @Override
            public void onItemClickListener(View v, int position) {
                Intent intent = new Intent();
                intent.setClass(PalBillItemActivity.this, ImagePreviewActivity.class);
                ArrayList<String> listPhotos = new ArrayList<>();
                for (int i = 0; i < listPhoto.size(); i++) {
                    listPhotos.add(listPhoto.get(i).getPhoto());
                }
                intent.putExtra(AllConstants.WHAT, listPhotos);
                intent.putExtra(AllConstants.ID, position);
                startActivity(intent);
            }
        });
        first = new ArrayList<>();
        second = new ArrayList<>();
        third = new ArrayList<>();
        rvPhoto.setLayoutManager(new GridLayoutManager(this, 3));
        rvPhoto.setAdapter(adapterPhoto);
//        巡更點異常
        rbPoint = findViewById(R.id.rb_point);
        rbPoint.setOnCheckedChangeListener(new OnCheckedChangeListener());
        etPoint = findViewById(R.id.et_point);
        etPoint.setEnabled(false);
        OnClickListener onClickListener = new OnClickListener();
//        創建事件報告
        findViewById(R.id.btn_create).setOnClickListener(onClickListener);
//        確定
        findViewById(R.id.btn_confirm).setOnClickListener(onClickListener);
        query.init();
        mPresenter.getData(query);
    }

    private void showDate(final int position) {
        OptionsPickerView<String> optionsPickerView = DateUtil.showDate(this, new DateUtil.OnSelectorCallback() {
            @Override
            public void onSelectListener(int options1, int options2, int options3) {
                firstPos = options1;
                hour = options2;
                minute = options3;
                adapterChoice.setInput(position,
                        first.get(options1) + " " + second.get(options2) + ":" + third.get(options3));
            }
        });
        optionsPickerView.setNPicker(first, second, third);
        optionsPickerView.setSelectOptions(firstPos, hour, minute);
        optionsPickerView.show();

    }

    /**
     * 設置選擇時間數據
     */
    private void getList() {
        if (first.size() == 0) {
            Calendar c = Calendar.getInstance();
            hour = c.get(Calendar.HOUR_OF_DAY);
            minute = c.get(Calendar.MINUTE);
            List<List<String>> dateList = DateUtil.getDateList(c);
            first.addAll(dateList.get(0));
            firstPos = Integer.parseInt(dateList.get(1).get(0));

            second.addAll(DateUtil.getNumList(24));
            third.addAll(DateUtil.getNumList(60));
        }
    }

    @Override
    public void onGetDataSuccess(ApiResultData<PagedList<PalBillItemDto>> apiResultData) {
        if (apiResultData.getStatus() != 2000) {
            ToastDialogUtils.getInstance().showInfoMessage(this, apiResultData.getMessage());
            return;
        }
        listChoice.addAll(apiResultData.getData().getList());
        adapterChoice.notifyDataSetChanged();
    }

    @Override
    public void onGetDataFails(Exception e) {
        ToastDialogUtils.getInstance().showInfoMessage(this, getString(R.string.network_error));
    }

    @Override
    public void onUploadImgSuccess(ApiResultData<String> apiResultData, int position) {
        if (apiResultData.getStatus() != 2000) {
            adapterPhoto.delete(position);
            ToastDialogUtils.getInstance().showInfoMessage(this, apiResultData.getMessage());
            return;
        }
        listPhoto.set(position,new CreatePalBillItemDto.ExctPhoto(OKHttpUtil.IMG_URL + apiResultData.getData()));
    }

    @Override
    public void onUploadImgFails(Exception e, int position) {
        adapterPhoto.delete(position);
        ToastDialogUtils.getInstance().showInfoMessage(this, getString(R.string.network_error));
    }

    @Override
    public void onUploadDataSuccess(ApiResultData<String> apiResultData) {
        if (apiResultData.getStatus() != 2000) {
            ToastDialogUtils.getInstance().showInfoMessage(this, apiResultData.getMessage());
            return;
        }
        setResult(1);
        finish();
    }

    @Override
    public void onUploadDataFails(Exception e) {
        ToastDialogUtils.getInstance().showInfoMessage(this, getString(R.string.network_error));
    }

    @Override
    public String getBillId() {
        return billId;
    }

    @Override
    public String getSiteId() {
        return siteId;
    }

    @Override
    public boolean getExct() {
        return rbPoint.isChecked();
    }

    @Override
    public String getExctRemark() {
        return etPoint.getText().toString().trim();
    }

    @Override
    public List<CreatePalBillItemDto.CreatePalBillItemFdbackDto> getItemFdbacks() {
        return listFd;
    }

    @Override
    public List<CreatePalBillItemDto.ExctPhoto> getExctPhotos() {
        for (int i = 0;i < listPhoto.size();i++){
            String photo = listPhoto.get(i).getPhoto();
            if (photo.startsWith(OKHttpUtil.IMG_URL)) {
                listPhoto.get(i).setPhoto(photo.substring(OKHttpUtil.IMG_URL.length()));
            }
        }
        return listPhoto;
    }

    @Override
    public CreatePalBillItemDto.Event getEvent() {
        return event;
    }

    @Override
    public void showLoading() {
        LoadingDialogUtils.getInstance().showLoading(this);
    }

    @Override
    public void hideLoading() {
        LoadingDialogUtils.getInstance().dismiss();
    }

    class OnClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_create:
                    Intent intent = new Intent(PalBillItemActivity.this, CreateReportActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString(AllConstants.PLAN, siteName);
                    bundle.putString(AllConstants.DESCRIBE, etPoint.getText().toString());
                    intent.putExtra(AllConstants.WHAT, bundle);
                    intent.putExtra(AllConstants.INFO_TYPE,1);
                    startActivityForResult(intent, 10);
                    break;
                case R.id.btn_confirm:
                    listFd.clear();
                    for (int i = 0; i < listChoice.size(); i++) {
                        PalBillItemDto dto = listChoice.get(i);
                        if (TextUtils.isEmpty(dto.getDefVal())) {
                            String msg = dto.getEnterType() == 3 && dto.getEnterLimit() != 3 ? getString(R.string.p_input) : getString(R.string.p_sel);
                            ToastDialogUtils.getInstance().showInfoMessage(PalBillItemActivity.this, msg + dto.getItemName());
                            return;
                        }
                        listFd.add(new CreatePalBillItemDto.CreatePalBillItemFdbackDto(dto.getItemId(), dto.getDefVal()));
                    }
                    mPresenter.uploadData();
                    break;
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != 0) {
            if (requestCode == AllConstants.PIC_GALLERY) {
                if (data != null && data.getData() != null) {
                    String path = FileUtils.getFilePathByUri(this, data.getData());
                    uploadImg(path);
                }
            } else if (requestCode == AllConstants.PIC_CAMERA) {
                Bitmap bitmap = PhotoUtil.getInstance().rotatingPic(PhotoUtil.getInstance().getAngle(), BitmapFactory.decodeFile(PhotoUtil.getInstance().imgUrl));
                String path = ImageUtil.getInstance().bitmapToUrl(this, bitmap);
                uploadImg(path);
            } else if (requestCode == 10 && resultCode == 1) {
                event = (CreatePalBillItemDto.Event) data.getSerializableExtra(AllConstants.WHAT);
            }
        }
    }

    private void uploadImg(String path) {
        adapterPhoto.add(new CreatePalBillItemDto.ExctPhoto(path));
        try {
            mPresenter.uploadImg(path, listPhoto.size() - 1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    class OnCheckedChangeListener implements CompoundButton.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            etPoint.setEnabled(isChecked);
        }
    }

    @Override
    public PalBillItemPresenter createPresenter() {
        return new PalBillItemPresenter();
    }

    @Override
    public void per() {

    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_patrol_item;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // 申请相机权限后返回
            if (requestCode == ComboPicDialog.PIC_CAREMA) {
                PhotoUtil.getInstance().toCamera(this);
            }
            // 申请读取图库权限后返回
            else if (requestCode == ComboPicDialog.PIC_GALLERY) {
                PhotoUtil.getInstance().toGallery(this);
            }
        }
    }
}